package com.cq.hd.member.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.constant.MsgConstant;
import com.cq.hd.common.constant.RedisKeyConstant;
import com.cq.hd.common.entity.hf.HfBusinessEnterApply;
import com.cq.hd.common.entity.hf.HfBusinessEnterOpenResult;
import com.cq.hd.common.entity.mq.NotifyMsgSendDto;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.dto.BusinessEnterApplyUpdateDto;
import com.cq.hd.member.api.dto.MerchantEnterApplyUpdateDto;
import com.cq.hd.member.api.vo.BusinessEnterApplyPageVo;
import com.cq.hd.member.api.vo.MerchantEnterApplyPageVo;
import com.cq.hd.member.config.LockUtils;
import com.cq.hd.member.mq.provider.BusinessEnterMsgProvider;
import com.cq.hd.member.mq.provider.MerchantEnterMsgProvider;
import com.cq.hd.member.mq.provider.NotifyMsgProvider;
import com.cq.hd.member.service.TbBusinessEnterApplyService;
import com.cq.hd.member.service.TbMerchantEnterApplyService;
import com.cq.hd.system.api.HfApi;
import com.cq.hd.system.api.HfRequestRecordApi;
import com.cq.hd.system.api.dto.HfRequestRecordSaveDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class HfMerchantCallbackBiz {

    @Autowired
    private TbBusinessEnterApplyService businessEnterApplyService;

    @Autowired
    private TbMerchantEnterApplyService merchantEnterApplyService;

    @Autowired
    private HfApi hfApi;

    @Autowired
    private BusinessEnterMsgProvider businessEnterMsgProvider;

    @Autowired
    private MerchantEnterMsgProvider merchantEnterMsgProvider;

    @Autowired
    private HfRequestRecordApi hfRequestRecordApi;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SmsBiz smsBiz;

    @Autowired
    private NotifyMsgProvider notifyMsgProvider;

    public Boolean merchantEntAuditCallback(JSONObject dataObj) {
        String subRespCode = dataObj.getString("sub_resp_code");
        String subRespDesc = dataObj.getString("sub_resp_desc");
        String reqSeqId = dataObj.getString("req_seq_id");
        String hfApplyNo = dataObj.getString("apply_no");
        String hfMerchantNo = dataObj.getString("huifu_id");
        // 审核结果；Y：审核通过，N：审核拒绝，F：失败
        String auditStatus = dataObj.getString("audit_status");
        // 审核描述
        String auditDesc = dataObj.getString("audit_desc");
        // 取现卡序列号
        String tokenNo = dataObj.getString("token_no");

        // 根据applyNo+huifuId查询商家/商户入驻记录表，根据状态判断是否需要更新对应的审核结果和审核描述
        List<BusinessEnterApplyPageVo> businessEnterApplyPageVos = businessEnterApplyService.listByApplyNoAndHfId(hfApplyNo, hfMerchantNo);
        if (!CollectionUtils.isEmpty(businessEnterApplyPageVos)) {
            BusinessEnterApplyPageVo businessEnterApplyPageVo = businessEnterApplyPageVos.get(0);

            // 添加汇付申请单记录（企业商户基本信息入驻，异步回调接口）
            HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
            hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.MERCHANT_ENT_AUDIT.getValue());
            hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
            hfRequestRecordSaveDto.setApplyNo(businessEnterApplyPageVo.getApplyNo());
            hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
            hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
            hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
            hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
            hfRequestRecordSaveDto.setRespCode(subRespCode);
            hfRequestRecordSaveDto.setRespDesc(subRespDesc);
            hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
            hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
            Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
            if (!saveRequestRecordState) {
                log.error("添加汇付申请单记录失败（企业商户基本信息入驻，异步回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
            }

            if (AuditStateEnum.WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getAuditState())
                    && SystemAuditStateEnum.HF_ENTER_WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getSystemAuditState())) {

                if ("Y".equals(auditStatus)) {
                    // 审核成功，更新系统审核状态=汇付基本信息入驻审核成功 和 取现卡序列号
                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    businessEnterApplyUpdateDto.setId(businessEnterApplyPageVo.getId());
                    businessEnterApplyUpdateDto.setWithdrawalCardNo(tokenNo);

                    // 调用商户业务开通接口去开通相关业务
                    HfBusinessEnterApply hfBusinessEnterApply = new HfBusinessEnterApply();
                    BeanUtils.copyProperties(businessEnterApplyPageVo, hfBusinessEnterApply);
                    HfBusinessEnterOpenResult hfBusinessEnterOpenResult = hfApi.merchantOpen(hfBusinessEnterApply).unpack();
                    if (StringUtils.isBlank(hfBusinessEnterOpenResult.getHuiFuId())) {
                        log.error("汇付审核商家入驻成功，调用商户业务开通接口失败，调用接口result：{}", hfBusinessEnterOpenResult.getResultData());

                        // 调用商户业务开通接口失败，系统审核状态=汇付基本信息入驻审核成功，管理后台核验处理后并再次申请调用
                        businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_ENTER_AUDIT_SUCCESS.getValue());
                        businessEnterApplyUpdateDto.setHfFailReason(hfBusinessEnterOpenResult.getResultData());
                    } else {
                        // 调用商户业务开通接口成功，系统审核状态=汇付商户业务开通待审核
                        businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_OPEN_WAIT_AUDIT.getValue());
                    }

                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        Throw.isBusinessException("更新系统审核状态=汇付商户业务开通待审核失败");
                    }
                } else {
                    // 审核拒绝/失败，更新审核状态=未通过，系统审核状态=汇付基本信息入驻审核拒绝
                    businessEnterApplyPageVo.setAuditState(AuditStateEnum.FAIL.getValue());
                    businessEnterApplyPageVo.setRefuseReason(auditDesc);
                    businessEnterApplyPageVo.setSystemAuditState(SystemAuditStateEnum.HF_ENTER_AUDIT_FAIL.getValue());
                    businessEnterApplyPageVo.setHfFailReason(auditDesc);

                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    BeanUtils.copyProperties(businessEnterApplyPageVo, businessEnterApplyUpdateDto);
                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        Throw.isBusinessException("更新审核拒绝/失败状态失败");
                    }

                    // 发送商家升级审核结果系统通知
                    NotifyMsgSendDto notifyMsgSendDto = new NotifyMsgSendDto();
                    notifyMsgSendDto.setUserId(businessEnterApplyPageVo.getUserId());
                    notifyMsgSendDto.setMsgState(NotifyMsgStateEnum.NO_READ.getValue());
                    notifyMsgSendDto.setRoleType(RoleTypeEnum.BUSINESS.getValue());
                    notifyMsgSendDto.setMsgType(NotifyMsgTypeEnum.AGENT_BUSINESS_ENTER_AUDIT.getValue());
                    notifyMsgSendDto.setContent(MsgConstant.AGENT_BUSINESS_ENTER_AUDIT_FAIL);
                    notifyMsgProvider.sendMsg(notifyMsgSendDto);

                    // 审核拒绝，发送入驻失败短信
                    smsBiz.sendEnterFailSms(businessEnterApplyPageVo.getBusinessName(), businessEnterApplyPageVo.getMobile());
                }
            }
        }
        else{
            // 兼容对公结算的商户入驻
            List<MerchantEnterApplyPageVo> merchantEnterApplyPageVos = merchantEnterApplyService.listByApplyNoAndHfId(hfApplyNo, hfMerchantNo);
            if (!CollectionUtils.isEmpty(merchantEnterApplyPageVos)) {
                log.info("企业商户基本信息入驻回调，商户入驻对公账户结算，hfApplyNo：{}，hfMerchantNo：{}", hfApplyNo, hfMerchantNo);
                MerchantEnterApplyPageVo merchantEnterApplyPageVo = merchantEnterApplyPageVos.get(0);

                // 添加汇付申请单记录（企业商户基本信息入驻，异步回调接口）
                HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
                hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.MERCHANT_ENT_AUDIT.getValue());
                hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
                hfRequestRecordSaveDto.setApplyNo(merchantEnterApplyPageVo.getApplyNo());
                hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
                hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
                hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
                hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
                hfRequestRecordSaveDto.setRespCode(subRespCode);
                hfRequestRecordSaveDto.setRespDesc(subRespDesc);
                hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
                hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
                Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
                if (!saveRequestRecordState) {
                    log.error("添加汇付申请单记录失败（企业商户基本信息入驻，异步回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
                }

                if (AuditStateEnum.WAIT_AUDIT.getValue().equals(merchantEnterApplyPageVo.getAuditState())
                        && SystemAuditStateEnum.HF_ENTER_WAIT_AUDIT.getValue().equals(merchantEnterApplyPageVo.getSystemAuditState())) {

                    if ("Y".equals(auditStatus)) {
                        // 审核成功，更新审核状态=审核成功，系统审核状态=汇付基本信息入驻审核成功 和 取现卡序列号
                        MerchantEnterApplyUpdateDto merchantEnterApplyUpdateDto = new MerchantEnterApplyUpdateDto();
                        merchantEnterApplyUpdateDto.setId(merchantEnterApplyPageVo.getId());
                        merchantEnterApplyUpdateDto.setAuditState(AuditStateEnum.SUCCESS.getValue());
                        merchantEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_ENTER_AUDIT_SUCCESS.getValue());
                        merchantEnterApplyUpdateDto.setWithdrawalCardNo(tokenNo);
                        boolean update = merchantEnterApplyService.updateMerchantEnterApplyById(merchantEnterApplyUpdateDto);
                        if (!update) {
                            log.error("更新商户系统审核状态=汇付基本信息入驻审核成功，hfApplyNo：{}，hfMerchantNo：{}", hfApplyNo, hfMerchantNo);
                            return false;
                        }

                        // 发送mq消息处理，异步处理商户入驻成功之后商户账号创建和绑定
                        merchantEnterMsgProvider.sendMsg(merchantEnterApplyPageVo.getId());
                    } else {
                        // 审核拒绝/失败，更新审核状态=未通过，系统审核状态=汇付基本信息入驻审核拒绝
                        merchantEnterApplyPageVo.setAuditState(AuditStateEnum.FAIL.getValue());
                        merchantEnterApplyPageVo.setRefuseReason(auditDesc);
                        merchantEnterApplyPageVo.setSystemAuditState(SystemAuditStateEnum.HF_ENTER_AUDIT_FAIL.getValue());
                        merchantEnterApplyPageVo.setHfFailReason(auditDesc);

                        MerchantEnterApplyUpdateDto merchantEnterApplyUpdateDto = new MerchantEnterApplyUpdateDto();
                        BeanUtils.copyProperties(merchantEnterApplyPageVo, merchantEnterApplyUpdateDto);
                        boolean update = merchantEnterApplyService.updateMerchantEnterApplyById(merchantEnterApplyUpdateDto);
                        if (!update) {
                            log.error("更新商户系统审核状态=汇付基本信息入驻审核拒绝失败，hfApplyNo：{}，hfMerchantNo：{}", hfApplyNo, hfMerchantNo);
                            return false;
                        }

                        // 审核拒绝，发送入驻失败短信
                        smsBiz.sendEnterFailSms(merchantEnterApplyPageVo.getMerchantName(), merchantEnterApplyPageVo.getMobile());
                    }
                }
            }
        }

        return true;
    }

    public Boolean merchantOpenAuditCallback(JSONObject dataObj) {
        String subRespCode = dataObj.getString("sub_resp_code");
        String subRespDesc = dataObj.getString("sub_resp_desc");
        String reqSeqId = dataObj.getString("req_seq_id");
        String hfApplyNo = dataObj.getString("apply_no");
        String hfMerchantNo = dataObj.getString("huifu_id");
        // 审核结果；Y：审核通过，N：审核拒绝，F：失败
        String auditStatus = dataObj.getString("audit_status");
        // 审核描述
        String auditDesc = dataObj.getString("audit_desc");

        // 只有审核状态=待审核，系统审核状态=汇付商户业务开通待审核才需要处理
        // 根据applyNo+huifuId查询商家/商户入驻记录表，根据状态判断是否需要更新对应的审核结果和审核描述
        List<BusinessEnterApplyPageVo> businessEnterApplyPageVos = businessEnterApplyService.listByHfId(hfMerchantNo);
        if (!CollectionUtils.isEmpty(businessEnterApplyPageVos)) {
            BusinessEnterApplyPageVo businessEnterApplyPageVo = businessEnterApplyPageVos.get(0);

            HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
            hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.MERCHANT_OPEN_AUDIT.getValue());
            hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
            hfRequestRecordSaveDto.setApplyNo(businessEnterApplyPageVo.getApplyNo());
            hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
            hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
            hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
            hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
            hfRequestRecordSaveDto.setRespCode(subRespCode);
            hfRequestRecordSaveDto.setRespDesc(subRespDesc);
            hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
            hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
            Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
            if (!saveRequestRecordState) {
                log.error("添加汇付申请单记录失败（商户业务开通，异步审核回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
            }

            if (AuditStateEnum.WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getAuditState())
                    && SystemAuditStateEnum.HF_OPEN_WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getSystemAuditState())) {
                if ("Y".equals(auditStatus)) {
                    // 如果审核成功，更新审核状态=待审核，系统审核状态=汇付商户业务开通待开通
                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    businessEnterApplyUpdateDto.setId(businessEnterApplyPageVo.getId());
                    businessEnterApplyUpdateDto.setAuditState(AuditStateEnum.WAIT_AUDIT.getValue());
                    businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_OPEN_WAIT.getValue());

                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        Throw.isBusinessException("更新系统审核状态=汇付商户业务开通待开通失败");
                    }
                } else {
                    // 如果审核失败，更新审核状态=待审核，系统审核状态=汇付商户业务开通审核拒绝
                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    businessEnterApplyUpdateDto.setId(businessEnterApplyPageVo.getId());
                    businessEnterApplyUpdateDto.setAuditState(AuditStateEnum.WAIT_AUDIT.getValue());
                    businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_OPEN_AUDIT_FAIL.getValue());
                    businessEnterApplyUpdateDto.setHfFailReason(auditDesc);

                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        Throw.isBusinessException("更新系统审核状态=汇付商户业务开通审核拒绝失败");
                    }
                }
            }
        }

        return true;
    }

    public Boolean merchantOpenBusinessCallback(JSONObject dataObj) {
        String subRespCode = dataObj.getString("sub_resp_code");
        String subRespDesc = dataObj.getString("sub_resp_desc");
        String reqSeqId = dataObj.getString("req_seq_id");
        String hfApplyNo = dataObj.getString("apply_no");
        String hfMerchantNo = dataObj.getString("huifu_id");
        // 通知类型     W:微信，A：支付宝，U:银联二维码，B:刷卡，E:全域资金管理
        String notifyType = dataObj.getString("notify_type");

        // 对huifu_id加锁
        String lockKey = MessageFormat.format(Constant.LOCK_FORMAT, "merchantOpenBusinessCallback:" + hfMerchantNo);
        try {
            LockUtils.blockLock(lockKey, Constant.AUTO_UNLOCK_SECOND);

            // 只有审核状态=待认证，系统审核状态=汇付商户业务开通待开通才需要处理（这里不需要判断状态限制，如果开通多个支付，比如银联和微信，则会出现多条回调记录数据，需要记录多条）
            //          需要对hfApplyNo加锁
            //                  如果是待认证，系统审核状态=汇付商户业务开通待开通，则需要更新状态，并且做商家入驻成功之后商家账号创建和绑定处理
            //                  如果是审核成功，则只要添加回调记录数据即可

            // 根据applyNo+huifuId查询商家/商户入驻记录表，根据状态判断是否需要更新对应的审核结果和审核描述
            List<BusinessEnterApplyPageVo> businessEnterApplyPageVos = businessEnterApplyService.listByHfId(hfMerchantNo);
//        List<BusinessEnterApplyPageVo> businessEnterApplyPageVos = businessEnterApplyService.listByApplyNoAndHfId(hfApplyNo, hfMerchantNo);
            if (!CollectionUtils.isEmpty(businessEnterApplyPageVos)) {
                BusinessEnterApplyPageVo businessEnterApplyPageVo = businessEnterApplyPageVos.get(0);

                HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
                hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.MERCHANT_OPEN_BUSINESS.getValue());
                hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
                hfRequestRecordSaveDto.setApplyNo(businessEnterApplyPageVo.getApplyNo());
                hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
                hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
                hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
                hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
                hfRequestRecordSaveDto.setRespCode(subRespCode);
                hfRequestRecordSaveDto.setRespDesc(subRespDesc);
                hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
                hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
                Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
                if (!saveRequestRecordState) {
                    log.error("添加汇付申请单记录失败（商户业务开通，异步开通回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
                }

                if ("W".equals(notifyType)) {
                    JSONArray regResultList = dataObj.getJSONArray("reg_result_list");
                    String regResultListStr = JSON.toJSONString(regResultList);
                    log.info("微信支付业务开通结果回调，{}", regResultListStr);
                    redisUtil.set(String.format(RedisKeyConstant.HF_WX_OPEN_RESULT_KEY, hfMerchantNo), regResultListStr);
                }

                if (AuditStateEnum.WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getAuditState())
                        && (SystemAuditStateEnum.HF_OPEN_WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getSystemAuditState())
                        || SystemAuditStateEnum.HF_OPEN_WAIT.getValue().equals(businessEnterApplyPageVo.getSystemAuditState()))
//                    || (AuditStateEnum.WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getAuditState())
//                    && SystemAuditStateEnum.HF_OPEN_WAIT.getValue().equals(businessEnterApplyPageVo.getSystemAuditState()))
                ) {
                    // 更新审核状态=待签约认证，系统审核状态=汇付商户业务开通成功
                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    businessEnterApplyUpdateDto.setId(businessEnterApplyPageVo.getId());
                    businessEnterApplyUpdateDto.setAuditState(AuditStateEnum.WAIT_AUTH.getValue());
                    businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_OPEN_SUCCESS.getValue());

                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        log.error("更新系统审核状态=汇付商户业务开通成功失败");
                        return false;
                    }
                }
            }

            return true;
        } finally {
            LockUtils.unlock(lockKey);
        }
    }

    public Boolean merchantSettleConfigAuditCallback(JSONObject dataObj) {
        String subRespCode = dataObj.getString("sub_resp_code");
        String subRespDesc = dataObj.getString("sub_resp_desc");
        String reqSeqId = dataObj.getString("req_seq_id");
        String hfApplyNo = dataObj.getString("apply_no");
        String hfMerchantNo = dataObj.getString("huifu_id");
        // 审核结果；Y：审核通过，N：审核拒绝，F：失败
        String auditStatus = dataObj.getString("audit_status");
        // 审核描述
        String auditDesc = dataObj.getString("audit_desc");
        String tokenNo = dataObj.getString("token_no");

        // 只有审核状态=待审核，系统审核状态=汇付商户业务开通待审核才需要处理
        // 根据applyNo+huifuId查询商家/商户入驻记录表，根据状态判断是否需要更新对应的审核结果和审核描述
        List<BusinessEnterApplyPageVo> businessEnterApplyPageVos = businessEnterApplyService.listByHfId(hfMerchantNo);
        if (!CollectionUtils.isEmpty(businessEnterApplyPageVos)) {
            BusinessEnterApplyPageVo businessEnterApplyPageVo = businessEnterApplyPageVos.get(0);

            HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
            hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.MERCHANT_SETTLE_CONFIG_OPEN_AUDIT.getValue());
            hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
            hfRequestRecordSaveDto.setApplyNo(businessEnterApplyPageVo.getApplyNo());
            hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
            hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
            hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
            hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
            hfRequestRecordSaveDto.setRespCode(subRespCode);
            hfRequestRecordSaveDto.setRespDesc(subRespDesc);
            hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
            hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
            Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
            if (!saveRequestRecordState) {
                log.error("添加汇付申请单记录失败（子账号开通，异步审核回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
            }

            // 审核状态=待审核，系统审核状态=子账户待开通或签约认证成功
            if (AuditStateEnum.WAIT_AUDIT.getValue().equals(businessEnterApplyPageVo.getAuditState())
                    && (SystemAuditStateEnum.SUB_ACCOUNT_WAIT_OPEN.getValue().equals(businessEnterApplyPageVo.getSystemAuditState())
                    || SystemAuditStateEnum.SIGN_SUCCESS.getValue().equals(businessEnterApplyPageVo.getSystemAuditState()))) {
                if ("Y".equals(auditStatus)) {
                    // 如果审核成功，更新审核状态=待审核，系统审核状态=子账户开通审核通过
                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    businessEnterApplyUpdateDto.setId(businessEnterApplyPageVo.getId());
                    businessEnterApplyUpdateDto.setAuditState(AuditStateEnum.SUCCESS.getValue());
                    businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.SUB_ACCOUNT_OPEN_AUDIT_SUCCESS.getValue());
                    businessEnterApplyUpdateDto.setWithdrawalCardNo(tokenNo);

                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        Throw.isBusinessException("更新系统审核状态=子账户开通审核通过失败");
                    }

                    // 发送mq消息处理，异步处理商家入驻成功之后商家账号创建和绑定
                    log.info("发送mq消息处理，异步处理商家入驻成功之后商家账号创建和绑定");
                    businessEnterMsgProvider.sendMsg(businessEnterApplyPageVo.getId());
                } else {
                    // 如果审核失败，更新审核状态=待审核，系统审核状态=子账户开通审核拒绝
                    BusinessEnterApplyUpdateDto businessEnterApplyUpdateDto = new BusinessEnterApplyUpdateDto();
                    businessEnterApplyUpdateDto.setId(businessEnterApplyPageVo.getId());
                    businessEnterApplyUpdateDto.setAuditState(AuditStateEnum.WAIT_AUDIT.getValue());
                    businessEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.SUB_ACCOUNT_OPEN_AUDIT_FAIL.getValue());
                    businessEnterApplyUpdateDto.setHfFailReason(auditDesc);

                    boolean update = businessEnterApplyService.updateBusinessEnterApplyById(businessEnterApplyUpdateDto);
                    if (!update) {
                        Throw.isBusinessException("更新系统审核状态=子账户开通审核拒绝失败");
                    }
                }
            }
        }

        return true;
    }

    public Boolean merchantEntIndvAuditCallback(JSONObject dataObj) {
        String subRespCode = dataObj.getString("sub_resp_code");
        String subRespDesc = dataObj.getString("sub_resp_desc");
        String reqSeqId = dataObj.getString("req_seq_id");
        String hfApplyNo = dataObj.getString("apply_no");
        String hfMerchantNo = dataObj.getString("huifu_id");
        // 审核结果；Y：审核通过，N：审核拒绝，F：失败
        String auditStatus = dataObj.getString("audit_status");
        // 审核描述
        String auditDesc = dataObj.getString("audit_desc");
        // 取现卡序列号
        String tokenNo = dataObj.getString("token_no");

        // 查询商户入驻记录表,根据状态判断是否需要更新对应的审核结果和审核描述
        List<MerchantEnterApplyPageVo> merchantEnterApplyPageVos = merchantEnterApplyService.listByApplyNoAndHfId(hfApplyNo, hfMerchantNo);
        if (CollectionUtils.isEmpty(merchantEnterApplyPageVos)) {
            log.error("未找到商户入驻记录，hfApplyNo：{}，hfMerchantNo：{}", hfApplyNo, hfMerchantNo);
        } else {
            MerchantEnterApplyPageVo merchantEnterApplyPageVo = merchantEnterApplyPageVos.get(0);

            // 添加汇付申请单记录（个人商户基本信息入驻，异步回调接口）
            HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
            hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.MERCHANT_ENT_INDV_AUDIT.getValue());
            hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
            hfRequestRecordSaveDto.setApplyNo(merchantEnterApplyPageVo.getApplyNo());
            hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
            hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
            hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
            hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
            hfRequestRecordSaveDto.setRespCode(subRespCode);
            hfRequestRecordSaveDto.setRespDesc(subRespDesc);
            hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
            hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
            Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
            if (!saveRequestRecordState) {
                log.error("添加汇付申请单记录失败（个人商户基本信息入驻，异步回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
            }

            if (AuditStateEnum.WAIT_AUDIT.getValue().equals(merchantEnterApplyPageVo.getAuditState())
                    && SystemAuditStateEnum.HF_ENTER_WAIT_AUDIT.getValue().equals(merchantEnterApplyPageVo.getSystemAuditState())) {

                if ("Y".equals(auditStatus)) {
                    // 审核成功，更新审核状态=审核成功，系统审核状态=汇付基本信息入驻审核成功 和 取现卡序列号
                    MerchantEnterApplyUpdateDto merchantEnterApplyUpdateDto = new MerchantEnterApplyUpdateDto();
                    merchantEnterApplyUpdateDto.setId(merchantEnterApplyPageVo.getId());
                    merchantEnterApplyUpdateDto.setAuditState(AuditStateEnum.SUCCESS.getValue());
                    merchantEnterApplyUpdateDto.setSystemAuditState(SystemAuditStateEnum.HF_ENTER_AUDIT_SUCCESS.getValue());
                    merchantEnterApplyUpdateDto.setWithdrawalCardNo(tokenNo);
                    boolean update = merchantEnterApplyService.updateMerchantEnterApplyById(merchantEnterApplyUpdateDto);
                    if (!update) {
                        log.error("更新商户系统审核状态=汇付商户业务开通待审核失败");
                        return false;
                    }

                    // 发送mq消息处理，异步处理商户入驻成功之后商户账号创建和绑定
                    merchantEnterMsgProvider.sendMsg(merchantEnterApplyPageVo.getId());
                } else {
                    // 审核拒绝/失败，更新审核状态=未通过，系统审核状态=汇付基本信息入驻审核拒绝
                    merchantEnterApplyPageVo.setAuditState(AuditStateEnum.FAIL.getValue());
                    merchantEnterApplyPageVo.setRefuseReason(auditDesc);
                    merchantEnterApplyPageVo.setSystemAuditState(SystemAuditStateEnum.HF_ENTER_AUDIT_FAIL.getValue());
                    merchantEnterApplyPageVo.setHfFailReason(auditDesc);

                    MerchantEnterApplyUpdateDto merchantEnterApplyUpdateDto = new MerchantEnterApplyUpdateDto();
                    BeanUtils.copyProperties(merchantEnterApplyPageVo, merchantEnterApplyUpdateDto);
                    boolean update = merchantEnterApplyService.updateMerchantEnterApplyById(merchantEnterApplyUpdateDto);
                    if (!update) {
                        log.error("更新商户审核拒绝/失败状态失败");
                        return false;
                    }

                    // 审核拒绝，发送入驻失败短信
                    smsBiz.sendEnterFailSms(merchantEnterApplyPageVo.getMerchantName(), merchantEnterApplyPageVo.getMobile());

                }
            }
        }

        return true;
    }

    public Boolean wxBusinessConfigCallback(JSONObject dataObj) {
        String subRespCode = dataObj.getString("sub_resp_code");
        String subRespDesc = dataObj.getString("sub_resp_desc");
        String reqSeqId = dataObj.getString("req_seq_id");
        String hfApplyNo = dataObj.getString("apply_no");
        String hfMerchantNo = dataObj.getString("huifu_id");

        // 查询商户入驻记录表,根据状态判断是否需要更新对应的审核结果和审核描述
        List<BusinessEnterApplyPageVo> businessEnterApplyPageVos = businessEnterApplyService.listByHfId(hfMerchantNo);
        if (CollectionUtils.isEmpty(businessEnterApplyPageVos)) {
            log.error("未找到商家入驻记录，hfApplyNo：{}，hfMerchantNo：{}", hfApplyNo, hfMerchantNo);
        } else {
            BusinessEnterApplyPageVo businessEnterApplyPageVo = businessEnterApplyPageVos.get(0);

            // 添加汇付申请单记录（微信商户配置，异步回调接口）
            HfRequestRecordSaveDto hfRequestRecordSaveDto = new HfRequestRecordSaveDto();
            hfRequestRecordSaveDto.setApplyType(HfRequestRecordApplyTypeEnum.WX_BUSINESS_CONFIG_NOTIFY.getValue());
            hfRequestRecordSaveDto.setRequestType(HfRequestRecordRequestTypeEnum.ASYNC.getValue());
            hfRequestRecordSaveDto.setApplyNo(businessEnterApplyPageVo.getApplyNo());
            hfRequestRecordSaveDto.setHuifuId(hfMerchantNo);
            hfRequestRecordSaveDto.setHfApplyNo(hfApplyNo);
            hfRequestRecordSaveDto.setDataResult(JSON.toJSONString(dataObj));
            hfRequestRecordSaveDto.setReqSeqId(reqSeqId);
            hfRequestRecordSaveDto.setRespCode(subRespCode);
            hfRequestRecordSaveDto.setRespDesc(subRespDesc);
            hfRequestRecordSaveDto.setCreateTime(LocalDateTime.now());
            hfRequestRecordSaveDto.setUpdateTime(LocalDateTime.now());
            Boolean saveRequestRecordState = hfRequestRecordApi.saveRequestRecord(hfRequestRecordSaveDto).unpack();
            if (!saveRequestRecordState) {
                log.error("添加汇付申请单记录失败（微信商户配置，异步回调接口），hfRequestRecordSaveDto：{}", JSON.toJSONString(hfRequestRecordSaveDto));
            }
        }

        return true;
    }
}
